<?php
namespace Home\Controller;

use Think\Controller;
use Think\Log;

class IndexController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->check_login();
    }

    public function create_where()
    {
        $user_id = session("user_id");
        $u       = M("user")->where(["id" => $user_id])->find();
        if ($u['role'] == 2) {
            $where['follow_user_id'] = ['like', '%' . $user_id . '%'];
            $where['cc_user_id']     = ['like', '%' . $user_id . '%'];
            $where['input_user_id']  = $user_id;
            $where['_logic']         = 'or';
        } else {
            $where['name'] = ['neq', ''];
        }

        return $where;
    }

    /**
     * 日程首页
     * @return [type] [description]
     */
    public function index()
    {
        $model              = M('task');
        $start_time         = strtotime(date('Y-m-d 00:00:00', time()));
        $end_time           = strtotime(date('Y-m-d 23:59:59', time()));
        $where              = $this->create_where();
        $where1["_complex"] = $where;
        $where1['end_time'] = ['between', [$start_time, $end_time]];
        $data               = $model->where($where1)->select();

        $user_id = session("user_id");
        $u       = M("user")->where(["id" => $user_id])->find();

        $this->assign('role', $u['role']);
        $this->assign('data', $data);
        $this->display('schedule');
    }

    /**
     * 首页日程展示
     * @return [type] [description]
     */
    public function nowDateTaskList()
    {
        $date       = I('post.');
        $model      = M('task');
        $start_time = strtotime($date['date'] . ' 00:00:00');
        $end_time   = strtotime($date['date'] . ' 23:59:59');
        $where      = $this->create_where();
        //_logic  用了这后，在家查询条件的处理方式
        $where1["_complex"] = $where;
        $where1['end_time'] = ['between', [$start_time, $end_time]];
        $data               = $model->where($where1)->select();
        if (count($data)) {
            foreach ($data as $key => $value) {
                $data[$key]['end_time'] = date('Y-m-d H:i', $value['end_time']);
            }
            $this->success($data);
        } else {
            $this->error([]);
        }
    }

    /**
     * 新建日程页面展示
     * @return [type] [description]
     */
    public function showTask()
    {
        $info = M("project")->where(['pid' => 0])->field('id,classname value')->select();
        foreach ($info as $k => $v) {
            $child = M("project")->where(['pid' => $v['id']])->field('id,classname value')->select();
            foreach ($child as $key1 => $value1) {
                $child[$key1]['title'] = $v['value'] . ',' . $value1['value'];
            }

            $info[$k]['childs'] = $child;
            $info[$k]['title']  = $v['value'];
            foreach ($child as $key => $value) {
                $childs = M("project")->where(['pid' => $value['id']])->field('id,classname value')->select();
                foreach ($childs as $key2 => $value2) {
                    $childs[$key2]['title'] = $value['title'] . ',' . $value2['value'];
                }

                $info[$k]['childs'][$key]["childs"] = $childs;
            }
        }

        foreach ($info as $key => $value) {
            $info[$key]['childs'] = array_filter($info[$key]['childs']);
            if ($info[$key]['childs'] && count($info[$key]['childs']) > 0) {
                $info[$key]['flag'] = 1;
            } else {
                $info[$key]['flag'] = 0;
            }
            foreach ($info[$key]['childs'] as $key1 => $value1) {
                if ($info[$key]['childs'][$key1]['childs'] && count($info[$key]['childs'][$key1]['childs']) > 0) {
                    $info[$key]['childs'][$key1]['flag'] = 1;
                } else {
                    $info[$key]['childs'][$key1]['flag'] = 0;
                }
            }
        }

        //exit(json_encode($info));
        $model = M('user');
        $data  = $model->select();
        $this->assign('data', $data);
        $this->assign('info', $info);
        $this->display('createSchedule');
    }

    /**
     * 修改日程--高级经半人
     * @return [type] [description]
     */
    public function editTask()
    {
        $id      = I('id');
        $user_id = session("user_id");
        $u       = M("user")->where(['id' => $user_id])->find();
        if ($u['role'] != 1) {
            $this->error("暂无权限", "index/index");
        }
        $info  = M("task")->where(["id" => $id])->find();
        $model = M('user');
        $data  = $model->select();
        $this->assign('data', $data);
        $this->assign('info', $info);
        $this->display('editSchedule');
    }

    /**
     * 修改日程--高级经半人 -- 提交
     * @return [type] [description]
     */
    public function doEditTask()
    {
        $id      = I('task_id');
        $follow  = I('follow');
        $cc      = I('cc');
        $user_id = session("user_id");

        $u = M("user")->where(['id' => $user_id])->find();
        if ($u['role'] != 1) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '无权限']);
        }

        $info = M("task")->where(["id" => $id])->find();
        if ($info['commit_status'] != 2) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '该任务当前无法操作']);
        }

        if ($follow) {
            $data['follow_user_id'] = $follow;
        } else {
            $data['follow_user_id'] = '';
        }

        if ($cc) {
            $data['cc_user_id'] = $cc;
        } else {
            $data['cc_user_id'] = '';
        }

        $data['audit_time']    = time();
        $data['audit_user_id'] = $user_id;
        $rs                    = M("task")->where(["id" => $id])->save($data);
        if ($rs) {
            $this->ajaxReturn(['status' => true, 'code' => 1001, 'msg' => '确认成功']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '系统异常']);
        }
    }

    /**
     * 个人页面展示
     * @return [type] [description]
     */
    public function showMine()
    {
        $user_id = session("user_id");
        $model   = M('user');
        $data    = $model->where(['id' => $user_id])->find();
        $this->assign('data', $data);
        $this->display('mine');
    }

    /**
     * 任务列表页面展示
     * @return [type] [description]
     */
    public function showList()
    {
        $model = M('task');
        $where = $this->create_where();
        $data  = $model->where($where)->order('end_time asc')->select();

        foreach ($data as $key => $value) {
            if ($value['status'] == 1) {
                $ydata[] = $value;
            } elseif ($value['status'] == 2) {
                $end_time = $value['end_time'];
                //距离结束天数
                $tmp               = ceil(($end_time - time()) / 86400);
                $data[$key]['day'] = $tmp;
                $value['day']      = $tmp;
                if ($tmp > 0 && $tmp <= 3) {
                    $data[$key]['style'] = 'red';
                    $value['style']      = 'red';
                } elseif ($tmp >= 4 && $tmp <= 5) {
                    $data[$key]['style'] = 'yellow';
                    $value['style']      = 'yellow';
                } else {
                    $data[$key]['style'] = '';
                    $value['style']      = '';
                }
                $wdata[] = $value;
            }
        }

        $user_id = session("user_id");
        $u       = M("user")->where(["id" => $user_id])->find();

        $this->assign('role', $u['role']);
        $this->assign('ydata', $ydata); //完成
        $this->assign('wdata', $wdata); //未完成
        $this->assign('data', $data);
        $this->display('task');
    }

    /**
     * 任务列表页面展示
     * @return [type] [description]
     */
    public function showTaskDetail()
    {
        $taskId           = I('get.id');
        $model            = M('task');
        $where['id']      = $taskId;
        $data             = $model->where($where)->find();
        $userInfo         = M('user')->where('id=' . $data['input_user_id'])->find();
        $followIds        = explode(',', $data['follow_user_id']);
        $useeModel        = M('user');
        $where1['id']     = ['in', $followIds];
        $followInfo       = $useeModel->where($where1)->select();
        $follow_user_name = '';
        foreach ($followInfo as $key => $value) {
            $follow_user_name .= $value['nickname'] . ',';
        }
        $follow_user_name         = substr($follow_user_name, 0, strlen($follow_user_name) - 1);
        $data['input_user_name']  = $userInfo['nickname'];
        $data['follow_user_name'] = $follow_user_name;
        //图片显示
        $path      = geturl() . $data['commit_info'];
        $base64Img = file_get_contents($path);

        $this->assign('data', $data);
        $this->assign('base64Img', $base64Img);
        $this->display('taskDetail');
    }

    /**
     * 建立任务
     */
    public function addTask()
    {
        $arr                          = I('post.', array(), 'trim');
        $insertData['name']           = $arr['content']; //项目名称
        $insertData['end_time']       = strtotime($arr['datetime']);
        $insertData['project_id']     = $arr['xmid']; // 项目
        $insertData['project_name']   = $arr['xm']; // 项目
        $insertData['input_user_id']  = session("user_id"); //创建项目人的id
        $insertData['follow_user_id'] = $arr['follow']; //跟进人
        $insertData['cc_user_id']     = $arr['cc']; //抄送人
        $insertData['remark']         = $arr['remark']; //说明
        $insertData['add_time']       = time();
        $insertData['update_time']    = '';
        $insertData['status']         = 2;

        if (!$insertData['name']) {
            $this->error('请填写日程内容！');
        }

        if (!$insertData['project_id']) {
            $this->error('请选择所属项目！');
        }

        $res = M('task')->add($insertData);
        if ($res) {
            //保存任务编号 日期+id
            M('task')->where('id='.$res)->save(['sn'=>date('Ymd').$res]);
            $this->success('创建任务成功', U('showList'));

        } else {
            $this->error('创建任务失败');
        }
    }

    /**
     * 查找出来有任务的日期用作前端的样式判断
     * @return boolean [description]
     */
    public function hasTaskDate()
    {
        $m     = I('post.')['m'];
        $month = I('post.')['month'];
        $year  = I('post.')['year'];
        $t     = $m + 1;
        if ($year) {
            $BeginDate = date($year . '-' . $month . '-01', strtotime(date("Y-m-d")));
            $day       = date($year . '-' . $month . '-d', strtotime("$BeginDate +$t month -1 day"));
        } else {
            $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
            $day       = date('Y-m-d', strtotime("$BeginDate +$t month -1 day"));
        }

        $start_time = strtotime($BeginDate . ' 00:00:00');
        $end_time   = strtotime($day . ' 23:59:59');

        $model              = M('task');
        $where              = $this->create_where();
        $where1["_complex"] = $where;
        $where1['end_time'] = ['between', [$start_time, $end_time]];
        $data               = $model->where($where1)->select();

        $ret = [];
        foreach ($data as $key => $value) {
            $tmp = date('d', $value['end_time']);
            //如果是01这样的 返回1
            if (substr($tmp, 0, 1) === '0') {
                $tmp = str_replace('0', '', $tmp);
            }
            $ret[] = $tmp;
        }
        $this->ajaxReturn($ret);
    }

    /**
     * 新建任务项目选择
     * @return [type] [description]
     */
    public function project()
    {
        $info = M("project")->where(['pid' => 0])->field('id,classname value')->select();
        foreach ($info as $k => $v) {
            $child              = M("project")->where(['pid' => $v['id']])->field('id,classname value')->select();
            $info[$k]['childs'] = $child;
            foreach ($child as $key => $value) {
                $childs                             = M("project")->where(['pid' => $value['id']])->field('id,classname value')->select();
                $info[$k]['childs'][$key]["childs"] = $childs;
            }
        }

        $arr = [
            'id'     => 0,
            'value'  => '',
            'childs' => [],
        ];
        foreach ($info as $key => $value) {
            array_unshift($info[$key]['childs'], $arr);
            foreach ($info[$key]['childs'] as $key1 => $value1) {
                if (isset($value1['childs'])) {
                    array_unshift($info[$key]['childs'][$key1]['childs'], $arr);
                }
            }
        }

        exit(json_encode($info));
    }

    /**
     * 完成存档
     * @return [type] [description]
     */
    public function commit()
    {
        $task_id   = I('task_id', '', 'trim');
        $status    = I('status', '', 'trim');
        $base64Img = I('base64Img', '', 'trim');
        $user_id   = session("user_id");

        $path = geturl() . '/Public/txt/';
        $rs   = file_put_contents($path . $task_id . '.txt', $base64Img);
        Log::write('保存base64图片返回结果：' . $rs);

        $info = M("task")->where(["id" => $task_id])->find();
        if ($info['commit_status'] != '2') {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '改任务已存档，不能重复存档']);
        }

        if (!in_array($user_id, explode(',', $info['follow_user_id']))) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '非任务跟进人不能完成存档']);
        }

        $data = [
            'status'         => $status,
            'commit_status'  => $status,
            'commit_info'    => '/Public/txt/' . $task_id . '.txt',
            'commit_user_id' => $user_id,
            'commit_time'    => time(),
        ];
        if (M('task')->where(['id' => $task_id])->save($data)) {
            $this->ajaxReturn(['status' => true, 'code' => 1001, 'msg' => '存档成功']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '系统异常']);
        }
    }
}
